﻿function index_get() {
	//首页公告
	var data1;
	var tbody = "";
	$.ajax({
		type: "POST",
		url: "http://113.54.11.32/cars/public/index.php/user/user/inform",
		dataType: "text", //后台返回格式问题
		success: function (data) {
			data1 = eval('(' + data + ')');
			jQuery.each(data1, function (i, value) {
				var trs = '<div class="container things"><h3>' + value.title + '</h3><p><small>发布时间：' + value.time + '</small></p><p>' + value.content + '</p></div>';
				tbody += trs;
			});
			$("#article").append(tbody);
		},
		error: function (data) {
			// alert("请检查是否连接网络");
			alert(data);
		}
	});
}


//登录验证
function fun_login() {
	var formData = $("#loginForm").serializeJson();
	//var formData.role);
	console.log(formData.role);

	if (formData.role == 'admin') {
		//管理员登录 post请求然后跳转页面
		$.post('http://113.54.11.32/cars/public/index.php/admin/admin/login', {
			admin: formData.username,
			password: formData.password,
		}, function (data) {
			data1 = data1 = eval('(' + data + ')');
			if (data1 != 0) {
				//得到管理员登陆信息 并存入session中 session中，2代表用户
				console.log(data1[0].campus);
				sessionStorage.campus = data1[0].campus;
				alert("登录成功");
				sessionStorage.user = 1;
				//跳转至管理员界面
				location.href = "index.html";
			} else {
				alert("账号或密码错误！请重新登陆！");
				sessionStorage.user = 0;
				sessionStorage.campus = "";
				window.location.reload();
			}
		}, 'text')
	} else if (formData.role == 'user') {
		// console.log(1);
		$.post('http://113.54.11.32/cars/public/index.php/user/user/login', {
			username: formData.username,
			password: formData.password,
		}, function (data) {
			data1 = eval('(' + data + ')');
			console.log(data1);
			if (data1 != 0) {
				//得到用户登陆名 并存入session中 session中，2代表用户
				console.log(data1[0].username);
				sessionStorage.username = data1[0].username;
				alert("登录成功");
				sessionStorage.user = 2;
				//跳转至用户界面
				location.href = "index.html";
			} else {
				alert("账号或密码输入错误！请选择正确的登陆身份！请重新登陆！");
				sessionStorage.user = 0;
				sessionStorage.username = "";
				window.location.reload();
			}
		}, 'text')
	} else {
		//请选择用户或者管理员
		alert("请选择用户或者管理员");
		window.location.reload();
	}
}

//退出
function tuichuClick() {
	sessionStorage.user = 0;
	sessionStorage.username = "";
	sessionStorage.campus = "";
	window.location = "../index/index.html";
}

//登录用户与管理员显示
window.onload = function () {
	if (sessionStorage.user == 1) {
		loginWho.innerHTML = '<li class="dropdown"><a href="login.html" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">管理员控制台<span class="caret"></span></a><ul class="dropdown-menu"><li><a href="../admin/addCar.html">临时车辆添加</a></li><li><a href="../admin/dealApplication.html">短期预约处理</a></li><li><a href="../admin/search.html">预约历史记录</a></li><li><a href="../admin/getQrCode.html">二维码生成</a></li><li role="separator" class="divider"><li><a href="../admin/admin_article.html">添加公告</a></li><li><a href="javascript:void(0)" onclick="tuichuClick()">退出</a></li></li></ul></li>';
	} else if (sessionStorage.user == 2) {
		loginWho.innerHTML = '<li class="dropdown"><a href="login.html" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">用户控制台<span class="caret"></span></a><ul class="dropdown-menu"><li><a href="../user/userOrder.html">短期车辆预约</a></li><li><a href="../user/userResults.html">申请结果</a></li><li role="separator" class="divider"><li><a href="javascript:void(0)" onclick="tuichuClick()">退出</a></li></li></ul></li>';
	} else {
		loginWho.innerHTML = '<li><a href="../index/login.html">登录</a></li>';
	}
}


//！！！用户功能！！！

//用户 申请结果回显
function userRes() {


	var data4;
	var tbody2 = "";
	$.ajax({
		type: "POST",
		url: "http://113.54.11.32/cars/public/index.php/user/user/myorder",
		// data:{
		// 	currentpage:1,
		// },
		dataType: "text", //后台返回格式问题
		success: function (data) {
			// data3 = data.slice(3);
			data2 = eval('(' + data + ')');
			//console.log(data2);
			jQuery.each(data2, function (i, value) {
				var trs = "<tr><td>" + value.id + "</td> <td>" + value.name + "</td> <td>" + value.plate_id + "</td> <td>";
				if (value.campus == 0) {
					trs = trs + "温江" + "</td> <td>";
				}
				else if (value.campus == 1) {
					trs = trs + "雅安" + "</td> <td>";
				}
				else {
					trs = trs + "都江堰" + "</td> <td>";
				}

				//var date3 = new Date(parseInt(value.beginDate) * 1000);
				//Y3 = date3.getFullYear() + '-';
				//M3 = date3.getMonth() + 1 + '-';
				//D3 = date3.getDate() + ' ';
				//date3 = Y3 + M3 + D3;

				//var date4 = new Date(parseInt(value.endDate) * 1000);
				//Y4 = date4.getFullYear() + '-';
				//M4 = date4.getMonth() + 1 + '-';
				//D4 = date4.getDate() + ' ';
				//date4 = Y4 + M4 + D4;
				//最终的时间
				//var res_data = date3 + " 至 " + date4;
				var res_data = value.begin_date + " 至 " + value.end_date;

				trs = trs + res_data + "</td><td>";
				//判断拒绝理由是否为空
				if (!value.refuse) {
					trs += "无";
				}
				else {
					trs += value.refuse;
				}

				//申请结果判断，2：未处理；1：通过；0：拒绝。
				if (value.status == 2) {
					trs += "</td>" + "<td><font color='black'>未处理</font></td>";
				}
				else if (value.status == 1) {
					trs += "</td>" + "<td><font color='green'>通过</font></td>";
				}
				else {
					trs += "</td>" + "<td><font color='red'>拒绝</font></td>";
				}

				trs = trs + "</tr>"

				tbody2 += trs;
			});
			$("#userInstrument").append(tbody2);
		},
		error: function (data) {
			alert("接收失败,code:" + data.status);
		}
	});
}


// 序列化表单，将其转化为json格式
$.fn.serializeJson = function () {
	var arr = this.serializeArray();
	var json = {};
	arr.forEach(function (item) {
		var name = item.name;
		var value = item.value;
		if (!json[name]) {
			json[name] = value;
		} else if ($.isArray(json[name])) {
			json[name].push(value);
		} else {
			json[name] = [json[name], value];
		}
	});
	return json;
}

//用户预约
function chuan_application() {
	var formData = $("#applicationForm").serializeJson();
	console.log(formData);

	//判断校区
	school = formData.campus;
	if (school == '都江堰校区') {
		school = 2;
	}
	else if (school == '雅安校区') {
		school = 1;
	}
	else {
		school = 0;
	}
	//console.log(school);

	var beginTime_res = formData.beginTime + " 00:00:00";
	var endTime_res = formData.endTime + " 23:59:59";
	//console.log(beginTime_res, endTime_res);

	$.post('http://113.54.11.32/cars/public/index.php/user/user/order', {
		beginDate: beginTime_res,
		endDate: endTime_res,
		plate_id: formData.carNumber,
		name: formData.userName,
		phone: formData.comeTelephone,
		campus: school,
		reason: formData.reason,
	}, function (data) {
		console.log(data)
		if (data == 1) {
			alert("递交申请成功!");
			window.location.reload();
		} else if (data == 0) {
			alert("递交申请失败!请检查是否填写表单完整。");
			window.location.reload();
		} else if (data == 2) {
			alert("预约失败！请检查网络或者重新登陆！");
			window.location.reload();
		} else if (data == -1) {
			alert("本周已经预约次数已经三次！请下周再预约！");
			window.location.reload();
		}
	}, 'text')
}

//！！！管理员功能！！！


//管理员添加临时预约车辆
function adminAdd() {
	var formData = $("#applicationForm").serializeJson();
	console.log(formData);

	var beginTime_res = formData.beginTime + " 00:00:00";
	var endTime_res = formData.endTime + " 23:59:59";
	console.log(beginTime_res, endTime_res);

	/*
	// 蓝卡云 API 预约车下放
	$.post('http://蓝卡云ip:端口/bcopenapi/out/synBookingCar', {
		"parkNumber": "p180808080808",
		"datas": [{
			"plate": formData.carNumber,
			"start": beginTime_res,
			"end": endTime_res,
			"areaId": "0",
			"flag": "1",
			"charge": "0",
			"bookOrderId": "",
			"bookOrderTime": "",
			"letInEndTime": beginTime_res,
			"letInStartTime": endTime_res,
			"memo": "",
		},
		{}
		]
	}, function (data) {
		console.log(data)
		if (data["status"] == "success") {
			$.post('http://113.54.11.32/cars/public/index.php/admin/admin/temporary', {
				beginDate: beginTime_res,
				endDate: endTime_res,
				plate_id: formData.carNumber,
				name: formData.comerName,
				phone: formData.comerTelephone,
			}, function (data) {
				console.log(data)
				if (data == 1) {
					alert("递交申请成功!");
					window.location.reload();
				} else if (data == 0) {
					alert("递交申请失败!请检查是否填写表单完整。");
					window.location.reload();
				} else if (data == 2) {
					alert("预约失败！请检查网络或者重新登陆！");
					window.location.reload();
				}
			}, 'text')

	
		} else if (data["status"] == "fail") {
			alert("预约失败！请检查网络或者重新登陆！");
			window.location.reload();
		}
	}, 'text')
	*/


	//原通过管理员添加预约方法
	$.post('http://113.54.11.32/cars/public/index.php/admin/admin/temporary', {
		beginDate: beginTime_res,
		endDate: endTime_res,
		plate_id: formData.carNumber,
		name: formData.comerName,
		phone: formData.comerTelephone,
	}, function (data) {
		console.log(data)
		if (data == 1) {
			alert("递交申请成功!");
			window.location.reload();
		} else if (data == 0) {
			alert("递交申请失败!请检查是否填写表单完整。");
			window.location.reload();
		} else if (data == 2) {
			alert("预约失败！请检查网络或者重新登陆！");
			window.location.reload();
		}
	}, 'text')


}

//时间格式化
Date.prototype.Format = function (fmt) { //author: meizz   
	    var o = {  
	        "M+": this.getMonth() + 1, //月份   
	        "d+": this.getDate(), //日   
	        "H+": this.getHours(), //小时   
	        "m+": this.getMinutes(), //分   
	        "s+": this.getSeconds(), //秒   
	        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
	        "S": this.getMilliseconds() //毫秒   
	    };  
	    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
	    for (var k in o)  
	    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));  
	    return fmt;  
	}; 

//管理员处理车辆预约申请
//同意申请
function adminYes(id_value) {
	var id_res1 = id_value;
	//alert(Sname+psw);
	console.log(id_res1);
	$.post('http://113.54.11.32/cars/public/admin/admin/id_data', {
		id: id_res1
	}, function (data) {
		//是否从本地服务器获取到的该 id 的预约信息


		if (data) {
			// 蓝卡云 API 预约车下放
			// 1、请求参数的具体意义，2、厂库编号，3、学校蓝卡云 ip：端口
			var datas = {
            "parkNumber": "p200604131236",
					"datas": [{
						"plate": data["plate_id"],
						"start": data["begin_date"],
						"end": data["end_date"],
						"areaId": "0",
						"flag": "1",
						"charge": "0",
						"bookOrderId": id_res1,
						"bookOrderTime": new Date().Format("yyyy-MM-dd HH:mm:ss"),
						"letInEndTime": data["begin_date"],
						"letInStartTime": data["end_date"],
						"memo": "",
		         }]
			};
			var resDatas = JSON.stringify(datas);
			console.log(typeof(resDatas), resDatas);


			var settings = {
			  	"async": true,
			  	"crossDomain": true,
			  	"url": "http://ai.bluecardsoft.com.cn/bcopenapi/out/synBookingCar",
			  	"method": "POST",
			  	"headers": {
			    "cache-control": "no-cache",
			    "content-type": "application/json",
			    "sign": "bf701fe8275d6b57eb75d5bffd4aed3a"
			  },
			  	"processData": false,
			  	"data": resDatas,
			}

			$.ajax(settings).done(function (response) {
				//console.log(data)
				var jsonData = eval('(' + response + ')');
				if (jsonData["status"] == "success") {
					//发送数据到本地服务器，记录
					$.post('http://113.54.11.32/cars/public/index.php/admin/admin/agree', {
						id: id_res1,
					}, function(data) {
						if(data == 1) {
							alert("同意成功");
							window.location.reload();
						} else {
							alert("同意失败");
							window.location.reload();
						}
					}, 'text')

				} else if (data["status"] == "fail") {
					alert("预约失败！请检查网络或者重新登陆！");
					window.location.reload();
				}
			}, 'text')

		} else {
			alert("同意失败");
			window.location.reload();
		}
	}, 'text')
}

var admin_reason; //score变量，用来存储用户拒绝理由。
//添加拒绝理由
function rec() {
	admin_reason = prompt("请输入您的拒绝理由(如果无，不输入即可)：");
}


//拒绝申请
function adminNo(id_value) {
	var id_res2 = id_value;
	//alert(Sname+psw);
	//console.log(id_res);
	rec();
	if (admin_reason == null) {
		alert("已取消拒绝");
		window.location.reload();
		return 0;
	}
	$.post('http://113.54.11.32/cars/public/index.php/admin/admin/refuse', {
		id: id_res2,
		refuse: admin_reason
	}, function (data) {
		if (data == 1) {
			alert("拒绝成功");
			window.location.reload();
		} else {
			alert("拒绝失败");
			window.location.reload();
		}
	}, 'text')
}

function getAllApplication() {
	//管理员申请管理
	var data3;
	var tbody1 = "";
	$.ajax({
		type: "POST",
		url: "http://113.54.11.32/cars/public/index.php/admin/admin/pending",
		dataType: "text", //后台返回格式问题
		success: function (data) {
			data3 = data
			//console.log(data3);
			// data3 = data3.slice(4);
			data3 = eval('(' + data3 + ')');
			jQuery.each(data3, function (i, value) {
				var trs = "<tr><td>" + value.id + "</td> <td>" + value.name + "</td><td>" + value.plate_id + "</td> <td>" + value.phone + "</td><td>";
				//var date1 = new Date(parseInt(value.beginDate) * 1000);
				//Y1 = date1.getFullYear() + '-';
				//M1 = date1.getMonth() + 1 + '-';
				//D1 = date1.getDate() + ' ';
				//date1 = Y1 + M1 + D1;

				//var date2 = new Date(parseInt(value.endDate) * 1000);
				//Y2 = date2.getFullYear() + '-';
				//M2 = date2.getMonth() + 1 + '-';
				//D2 = date2.getDate() + ' ';
				//date2 = Y2 + M2 + D2;
				//最终的时间
				var res_data = value.begin_date + " 至 " + value.end_date;


				//同意或拒绝两种操作方法
				trs += res_data + "</td><td>" + value.reason + "<td><a href='javascript:adminYes(" + value.id + ")' class='btn btn-primary btn-xs'>同意</a><a href='javascript:adminNo(" + value.id + ")' class='btn btn-danger btn-xs'>拒绝</a></td>" + "</tr>";

				tbody1 += trs;
			});
			$("#adminArticle").append(tbody1);
		},
		error: function (data) {
			alert("接收失败,code:" + data.status);
		}
	});
}

//搜索预约车辆
function getAllHistory() {
	//显示所有历史记录
	var data3;
	var tbody1 = "";
	$.ajax({
		type: "POST",
		url: "http://113.54.11.32/cars/public/index.php/admin/admin/pending",
		dataType: "text", //后台返回格式问题
		success: function (data) {
			data3 = data
			//console.log(data3);
			//data3 = data3.slice(4);console.log(data3); 
			data3 = eval('(' + data3 + ')');

			jQuery.each(data3, function (i, value) {
				var trs = "<tr><td>" + value.id + "</td> <td>" + value.name + "</td><td>" + value.plate_id + "</td> <td>" + value.phone + "</td><td>";

				var res_data = value.begin_date + " 至 " + value.end_date;

				trs += res_data + "</td><td>" + value.reason;

				//申请结果判断，2：未处理；1：通过；0：拒绝。
				if (value.status == 2) {
					trs += "</td>" + "<td><font color='black'>未处理</font></td>";
				}
				else if (value.status == 1) {
					trs += "</td>" + "<td><font color='green'>通过</font></td>";
				}
				else {
					trs += "</td>" + "<td><font color='red'>拒绝</font></td>";
				}

				trs = trs + "</tr>"

				tbody1 += trs;
			});
			$("#searchResult").append(tbody1);
		},
		error: function (data) {
			alert("接收失败,code:" + data.status);
		}
	});
}


//搜索目标车辆
function searchCar() {
	var formData = $("#searchText").serializeJson();
	//console.log(formData.carNumber);

	var data1;
	var tbody1 = "";
	$.ajax({
		type: "POST",
		url: "http://113.54.11.32/cars/public/index.php/admin/admin/seek",
		data: {
			plate_id: formData.carNumber,
		},
		dataType: "text", //后台返回格式问题
		success: function (data) {
			// $("#searchResult>tbody").html('');
			// jQuery删除table除第一行以外的所有行
			// $("#searchResult tbody tr").eq(0).nextAll().remove();
			data3 = data
			//console.log(data3);
			//data3 = data3.slice(4);console.log(data3); 
			if (data3 == -1) {
				alert("无该辆车记录");
				tbody1 = "<tr><td>无该辆车记录</td><td>无该辆车记录</td><td>无该辆车记录</td><td>无该辆车记录</td><td>无该辆车记录</td><td>无该辆车记录</td><td>无该辆车记录</td></tr>";
			}
			else if (data3 == 0) {
				alert("请输入正确的车牌号");
				tbody1 = "<tr><td>请输入正确的车牌号</td><td>请输入正确的车牌号</td><td>请输入正确的车牌号</td><td>请输入正确的车牌号</td><td>请输入正确的车牌号</td><td>请输入正确的车牌号</td><td>请输入正确的车牌号</td></tr>"
			}
			else {
				data3 = eval('(' + data3 + ')');
				console.log(data3);
				jQuery.each(data3, function (i, value) {
					var trs = "<tr><td>" + value.id + "</td> <td>" + value.name + "</td><td>" + value.plate_id + "</td> <td>" + value.phone + "</td><td>";

					var res_data = value.begin_date + " 至 " + value.end_date;

					trs += res_data + "</td><td>" + value.reason;

					//申请结果判断，2：未处理；1：通过；0：拒绝。
					if (value.status == 2) {
						trs += "</td>" + "<td><font color='black'>未处理</font></td>";
					}
					else if (value.status == 1) {
						trs += "</td>" + "<td><font color='green'>通过</font></td>";
					}
					else {
						trs += "</td>" + "<td><font color='red'>拒绝</font></td>";
					}

					trs = trs + "</tr>"

					tbody1 += trs;

				});
			}
			$("#searchResult tr:gt(0)").remove();
			$("#searchResult").append(tbody1);
		},
		error: function (data) {
			// alert("请检查是否连接网络");
			alert(data);
		}
	});
}

//显示所有历史记录
function searchAll() {
	window.location.href = "http://113.54.11.32/CARtest/admin/search.html";
}


//添加文章
function chuan_article() {
	var formData = $("#articleAdd").serializeJson();
	console.log(formData);

	$.post('http://113.54.11.32/cars/public/index.php/admin/admin/report', {
		title: formData.title,
		content: formData.content,
	}, function (data) {
		console.log(data)
		if (data == 1) {
			alert("公告创建成功!");
			window.location.reload();
		} else if (data == 0) {
			alert("公告创建失败!请检查是否填写表单完整。");
			window.location.reload();
		} else if (data == 2) {
			alert("公告创建失败！请检查网络或者重新登陆！");
			window.location.reload();
		}
	}, 'text')
}



//生成二维码图片
function getQrcode() {


	var formData = $("#applicationForm").serializeJson();
	var enUrl = encodeURI("http://113.54.11.32/CARtest/admin/qrCodeApplication.html" + "?unit=" + formData["comerName"] + "&beginDate=" + formData["beginTime"] + " 00:00:00&endDate=" + formData["endTime"] + " 23:59:59&reason=" + formData["reason"]);
	var res = "http://113.54.11.32/CARtest/admin/qrCodeApplication.html" + "?beginDate=" + formData["beginTime"] + " 00:00:00&endDate=" + formData["endTime"] + " 23:59:59&campus=" + sessionStorage.campus;

	//console.log(res);

	var qrcode = $('#qrcode').qrcode({
		width: 128,
		height: 128,
		text: res,
	});

}

//重置二维码生成页面
function refresh() {
	window.location.reload();
}


//判断二维码是否过期
function qr_BeOverdue() {
	//获取url上的二维码截止日期
	var reg = new RegExp("(^|&)" + "endDate" + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	var end_Time = Date.parse(r[2].slice(0, 10));

	//获取今天的时间
	var time = new Date();
	var m = time.getMonth() + 1;
	var t = time.getFullYear() + "-" + m + "-" + (time.getDate() - 1);
	var today_Time = Date.parse(t)

	if (end_Time < today_Time) {
		alert("对不起，该二维码已失效！");
		window.location.href = "../index/index.html";
	}


}


//二维码用户预约数据传输
function qr_application() {
	var formData = $("#applicationForm").serializeJson();
	console.log(formData);
	var test = window.location.search;
	console.log(test);
	var searchText = decodeURI(test);
	console.log(searchText);

	$.get('http://113.54.11.32/cars/public/index.php/user/user/qrcode' + searchText, {
		plate_id: formData["carNumber"],
		name: formData["userName"],
		phone: formData["comTelephone"],
	}, function (data) {
		console.log(data)
		if (data == 1) {
			alert("递交申请成功!");
			window.location.href = "../index/index.html";
		} else if (data == 0) {
			alert("递交申请失败!请检查是否填写表单完整。");
			window.location.reload();
		} else {
			alert("网络问题，请重新扫描二维码！");
			window.location.reload();
		}
	}, 'text')
}

//下载二维码图片
//判断浏览器类型
function myBrowser() {
	var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
	var isOpera = userAgent.indexOf("Opera") > -1;
	if (isOpera) {
		return "Opera"
	}; //判断是否Opera浏览器
	if (userAgent.indexOf("Firefox") > -1) {
		return "FF";
	} //判断是否Firefox浏览器
	if (userAgent.indexOf("Chrome") > -1) {
		return "Chrome";
	}
	if (userAgent.indexOf("Safari") > -1) {
		return "Safari";
	} //判断是否Safari浏览器
	if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
		return "IE";
	}; //判断是否IE浏览器
	if (userAgent.indexOf("Trident") > -1) {
		return "Edge";
	} //判断是否Edge浏览器
};

function downloadQrcode() {
	var canvas = $('#qrcode').find("canvas").get(0); //取到canvas

	var url = canvas.toDataURL('image/jpeg'); //把canvas转换成base64

	myBrowser(); //判断浏览器类型

	if (myBrowser() === "IE" || myBrowser() === "Edge") {
		var blob = canvas.msToBlob();
		window.navigator.msSaveBlob(blob, a + '.png');
	} else {
		$('#download').attr({
			href: url,
			download: name
		}).get(0).click();
	}
}
